﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiemensOPC;
using Opc.Ua;
using Opc.Ua.Client;
using VswService_V7.Config;
using VswService_V7.DataBase.Tables;
using VswService_V7.Utility;
using System.Data;

namespace VswService_V7.OPC.DB
{
	public  class PlsAddressDbData : SubscriptionDbDataBase
	{
		public PlsAddressDbData(SimaticOPCClient opc, NodeConfig nodes) : base(opc, nodes)
		{
            _plsInfo = new PLSInformation();

        }

        PLSInformation _plsInfo;
        string _Location = "PLS";

        public override void CreateSubscription()
		{
            opcServer.QuickAddMonitorItem(opcNodes.PlsAddress.GrpoupName,
                opcNodes.PlsAddress.PublishTime, 
                opcNodes.PlsAddress.SampleTime,
                opcNodes.PlsAddress.GetNodeAddress(),
                opcNodes.PlsAddress.GetNodeDisplayName(),
                SubscriptionHandle);
            opcServer.QuickAddMonitorItem(opcNodes.PlsPipeAddress.GrpoupName,
                opcNodes.PlsPipeAddress.PublishTime, 
                opcNodes.PlsPipeAddress.SampleTime,
				opcNodes.PlsPipeAddress.GetNodeAddress(), 
                opcNodes.PlsPipeAddress.GetNodeDisplayName(),
				SubscriptionHandlePls);
		}

        private void SubscriptionHandle(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                if (notification == null || notification.Value.Value == null)
                    return;
                if (monitoredItem.DisplayName == "Pls_Ask")
                {
                    bool ask;
                    if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                    {
                        if (ask)
                        {
                            Console.WriteLine(_Location + " ask: " + notification.Value);
                            Task.Run(() => HandlePLS());
                        }
                        else
                        {
                            opcServer.WriteValue("false", opcNodes.PlsAddress.Pls_Rsp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("SubscriptionHandlePLS", ex);
                throw ex;
            }

        }

        private void SubscriptionHandlePls(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
		{
			try
			{
				MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                if (notification == null || notification.Value.Value == null)
                    return;
                switch (monitoredItem.DisplayName)
				{
					case "Batch_No":
						{
                            _plsInfo.batchNo = notification.Value.Value.ToString();
							break;
						}
					case "Pipe_No":
						{
                            _plsInfo.pipeNumber = notification.Value.Value.ToString();
							break;
						}
					case "Head_Cut":
						{
                            _plsInfo.headCut = notification.Value.Value.ToString();
							break;
						}
                    case "Rear_Cut":
                        {
                            _plsInfo.rearCut = notification.Value.Value.ToString();
                            break;
                        }
                    case "Pipe_Length":
                        {
                            _plsInfo.length = notification.Value.Value.ToString();
                            break;
                        }            
					case "Quality_Code":
						{
                            _plsInfo.qualityCode = notification.Value.Value.ToString();
							break;
						}
                    case "Quality_Code2":
                        {
                            _plsInfo.qualityCode2 = notification.Value.Value.ToString();
                            break;
                        }
                    case "Scrap":
                        {
                            _plsInfo.scrap = notification.Value.Value.ToString();
                            break;
                        }

                    default:
						{
							break;
						}
				}
			}
			catch(Exception ex)
			{
                throw ex;
			}			
		}

        private async Task HandlePLS()
        {
            await Task.Delay(1000);
            if (_plsInfo.batchNo.Equals("0") || _plsInfo.pipeNumber.Equals("0"))
                return;
            Console.WriteLine(_Location + " handlePls start record");
            try
            {
                PIPE_INFO.UpdatePipeInfoPlsRecord(_plsInfo.GetFullPipeNo(), DateTime.Now, _plsInfo.headCut, _plsInfo.rearCut,_plsInfo.qualityCode,_plsInfo.qualityCode2,_plsInfo.length, _Location);
            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("HandlePLS", ex);
            }
            

            //PRINT!!!!
            opcServer.WriteValue("true", opcNodes.PlsAddress.Pls_Rsp);
        }
    }


    public class PLSInformation
    {
        public PLSInformation()
        {
            batchNo = "0";
            pipeNumber = "0";
            headCut = "0";
            rearCut = "0";
            length = "0";
            qualityCode = "0";
            qualityCode2 = "0";
            scrap = "0";
        }

        public string batchNo;
        public string pipeNumber;
        public string headCut;
        public string rearCut;
        public string length;
        public string qualityCode;
        public string qualityCode2;
        public string scrap;

        public string GetFullPipeNo()
        {
            int pipeNum = int.Parse(pipeNumber);
            string fullPipeNumber = batchNo + pipeNum.ToString("000");
            return fullPipeNumber;
        }


    }

}
